package com.bjpowernode.web;

import com.bjpowernode.model.TUser;
import com.bjpowernode.query.UserQuery;
import com.bjpowernode.result.R;
import com.bjpowernode.service.UserService;

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class UserController {

	@Autowired
	private UserService userService;

	/**
	 * 获取登录人信息
	 *
	 * @param authentication SpringSecurity登陆成功认证类
	 * @return 登录人信息
	 */
	@GetMapping("/login/info")
	public R loginInfo(Authentication authentication) {

		TUser tUser = (TUser) authentication.getPrincipal();

		return R.OK(tUser);
	}

	/**
	 * 免登录
	 * 
	 * @return 响应200状态码
	 */
	@GetMapping("/login/free")
	public R freeLogin() {
		return R.OK();
	}

	@GetMapping("/users")
	public R getUserPage(@RequestParam(value = "current", required = false) Integer current) {

		if (current == null) {
			current = 1;
		}

		return R.OK(userService.getUserByPage(current));
	}

	/**
	 * 获取用户详细信息
	 * 
	 * @param id 用户id
	 * @return 用户详细信息
	 */
	@GetMapping("/user/{id}")
	public R getUserDetail(@PathVariable(value = "id") Integer id) {
		TUser user = userService.getUserDetailById(id);
		return R.OK(user);
	}

	@PostMapping("/user/add")
	public R userSubmit(UserQuery userQuery, @RequestHeader(value = "Authorization") String token) {
		userQuery.setToken(token);
		int result = userService.save(userQuery);
		return result >= 1 ? R.OK() : R.FAIL();
	}

	@PutMapping("/user/update")
	public R userUpdate(UserQuery userQuery, @RequestHeader(value = "Authorization") String token) {
		userQuery.setToken(token);
		int result = userService.update(userQuery);
		return result >= 1 ? R.OK() : R.FAIL();
	}

	@DeleteMapping("/user/{id}")
	public R delUser(@PathVariable Integer id) {
		int result = userService.removeUser(id);
		return result >= 1 ? R.OK() : R.FAIL();
	}
	
	@DeleteMapping("/user/")
	public R batchDelUser(@RequestParam(value = "ids") String ids) {
		List<String> userIdList = Arrays.asList(ids.split(","));
		int result = userService.batchRemoveUser(userIdList);
		return result >= userIdList.size() ? R.OK() : R.FAIL();
	}

	/**
	 * 查询负责人数据
	 * 
	 * @return
	 */
	@GetMapping("/owner")
	public R getOwner() {
		return R.OK(userService.queryOwner());
	}

}
